package jp.co.redfox.archclub.poker.player;

import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

import jp.co.redfox.archclub.poker.Card;
import jp.co.redfox.archclub.poker.HandOverFlowException;
import jp.co.redfox.archclub.poker.hand.KindOfHand;

public class UserPlayer extends AbstractPlayer {

    private String name;
    private int coins;
    private Abator abator;
    

    private static final int default_money = 20;
    public UserPlayer(String name) {
        this(name, default_money);
    }
    public UserPlayer(String name, int money) {
        this.name = name;
        this.coins = money;
    }
    public void setAbator(Abator abator){
        this.abator = abator;
    }
    public String getName(){
        return name;
    }
    public String getFace(){
        if(this.abator == null)
            return "(・ε・)";
        return abator.getAa();
    }

    @Override
    public void payAnte() throws NoMoneyException {
        if (coins > 0)
            coins--;
        else
            throw new NoMoneyException(name + "cannot pay ante!");
    }
    
    @Override
    public void bet(int coins) throws NoMoneyException {
    }


    @Override
    public void changeCards() throws HandOverFlowException {
        showCards();
        // Confirm my hands hold or deal.
        System.out.println("Please select change card");
        Scanner scanner = new Scanner(System.in);
        String changeNumbers = scanner.nextLine();
        
        if(changeNumbers == null || changeNumbers.isEmpty())
            return;
        
        String[] split = changeNumbers.split("");

        Set<Card> s = new HashSet<>();
        for(int cnt = 0; cnt < split.length; cnt++){
            Integer idx ;
            try{
                idx = Integer.parseInt(split[cnt]);
            }catch(NumberFormatException nfe){
                continue;
            }
            if(idx < 1 || 5 < idx)
                continue;
            
            s.add(hand.getCards().get(idx - 1));
        }
        
        for(Card card: s)
            hand.discard(card);
        
        this.draw(s.size());
        
        showCards();
    }

    private void showCards() {
        System.out.println(this.name + "'s hands are as below");
        List<Card> cards = super.hand.getCards();
        StringBuilder sb = new StringBuilder();
        
        for (Card card : cards)
            sb.append(card);

        System.out.println(sb);
        KindOfHand hand = KindOfHand.judgeHand(super.hand);
        System.out.println(hand == null ? "HighCard" : hand.name());
    }
}
